using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using EzDeploy.Resources;

namespace EzDeploy.Core
{
    public class CopyAssemblyCommand : ICopyAssemblyCommand
    {
        public Result Run(IEnumerable<DeployGridItem> items, Project project)
        {
            int count = 0;
            var failedToCopy = new List<string>();

            if (File.Exists(project.AssemblyFile))
            {
                try
                {
                    File.Copy(project.AssemblyFile, Path.Combine(project.DeployedDirectory, Path.GetFileName(project.AssemblyFile)), project.OverWriteFile);
                    count++;
                }
                catch (IOException ex)
                {
                    return new Result(ResultType.Error, string.Format(MessageResource.CopyOperationFailedToCopyMainAssemblyFmt, ex.Message, Environment.NewLine));
                }
            }
            else
            {
                return new Result(ResultType.Error, string.Format(MessageResource.MainAssemblyNotFoundFmt, Path.GetFileName(project.AssemblyFile)));
            }

            foreach (DeployGridItem item in items)
            {
                if (item.DeploymentType == DeploymentType.Include)
                {
                    if (File.Exists(item.ItemFullPath))
                    {
                        try
                        {
                            File.Copy(item.ItemFullPath, Path.Combine(project.DeployedDirectory, item.ItemPath), project.OverWriteFile);
                            count++;
                        }
                        catch (IOException)
                        {
                            failedToCopy.Add(item.ItemFullPath);
                        }
                    }
                }
            }

            if (failedToCopy.Count > 0)
            {
                var buffer = new StringBuilder();
                buffer.AppendLine(string.Format(MessageResource.CopyOperationErrorSummaryFmt, count.ToString(), failedToCopy.Count.ToString(), Environment.NewLine));

                foreach (string fileName in failedToCopy)
                    buffer.AppendFormat("- {0}{1}", Path.GetFileName(fileName), Environment.NewLine);

                return new Result(ResultType.Error, buffer.ToString());
            }

            return new Result(ResultType.Success, string.Format(MessageResource.CopyOperationSuccessSummaryFmt, count));
        }
    }
}
